<template>
  <div class="index">
    <head-text titleText="商品管理"></head-text>
    <div class="list-content">
      <div class="filter-area">
        <Search :searchData="searchData" :searchItem="searchItem"></Search>
        <div class="operate-area">
          <el-button @click="add" plain type="success" size="mini"
            >添加商品</el-button
          >
          <el-button @click="exp" plain type="success" size="mini"
            >导出</el-button
          >
        </div>
      </div>
      <div class="table-title">
        <span></span>
        <h5>商品列表</h5>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        size="mini"
        v-if="hackReset"
      >
        <el-table-column type="index" width="50" align="center">
        </el-table-column>
        <!-- <el-table-column
          prop="id"
          label="商品ID"
          align="center"
          min-width="110"
        >
        </el-table-column> -->
        <el-table-column
          prop="productName"
          label="商品名称"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column label="商品图" align="center" width="120">
          <template slot-scope="scope">
            <div>
              <img
                :src="scope.row.imgUrl"
                class="img-size"
                alt=""
                v-image-preview
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="categoryName"
          label="商品分类"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="currentPrice"
          label="商品价格(元)"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="referActivityName"
          label="关联活动"
          align="center"
          :show-overflow-tooltip="true"
          width="140"
        >
        </el-table-column>
        <!-- <el-table-column
          prop="referActivityDate"
          label="关联活动日期"
          align="center"
          width="120"
        >
        </el-table-column> -->
        <el-table-column
          prop="totalStock"
          label="总库存（个）"
          align="center"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="stock"
          label="剩余库存（个）"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="purchaseLimit"
          label="限购数量"
          align="center"
          min-width="70"
        >
        </el-table-column>

        <el-table-column
          prop="sort"
          label="排序码"
          align="center"
          min-width="70"
        >
        </el-table-column>
        <!-- <el-table-column prop="venueFloor" label="楼层" align="center">
          <template slot-scope="scope">
            <div>
              {{ scope.row.venueFloor | floorFilter }}
            </div>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="isDraft"
          label="商品状态"
          align="center"
          min-width="80"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.isDraft | goodsStatus }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="shelfTime"
          label="上架时间"
          align="center"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="offShelfTime"
          label="下架时间"
          align="center"
          width="150"
        >
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="warning"
              style="margin: 5px"
              plain
              size="mini"
              @click="shelf(scope.row)"
              v-if="scope.row.isDraft != 3"
              >上架</el-button
            >
            <el-button
              type="warning"
              style="margin: 5px"
              plain
              size="mini"
              @click="offShelf(scope.row)"
              v-if="scope.row.isDraft == 3 || scope.row.isDraft == 2"
              >下架</el-button
            >
            <el-button
              type="primary"
              style="margin: 5px"
              plain
              size="mini"
              @click="edit(scope.row)"
              v-if="scope.row.isDraft == 4"
              >编辑商品</el-button
            >
            <el-button
              type="primary"
              style="margin: 5px"
              plain
              size="mini"
              @click="edit(scope.row)"
              v-if="scope.row.isDraft == 1"
              >编辑草稿</el-button
            >
            <el-button
              type="primary"
              style="margin: 5px"
              plain
              size="mini"
              @click="view(scope.row)"
              >查看</el-button
            >
            <el-button
              type="primary"
              style="margin: 5px"
              plain
              size="mini"
              @click="mangeInventory(scope.row)"
              v-if="scope.row.isDraft == 4"
              >修改库存</el-button
            >
            <el-button
              type="danger"
              style="margin: 5px"
              plain
              size="mini"
              v-if="scope.row.isDraft == 4 || scope.row.isDraft == 1"
              @click="deleteGoods(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <page
        :nowPage="nowPage"
        :total="total"
        :limit="limit"
        @pageChange="onPageChange"
        @sizeChange="onSizeChange"
        v-if="pageReset"
      />
    </div>
    <dialog-com :dialogObj="dialogObj" @reflash="getList"></dialog-com>
  </div>
</template>
<script>
import Search from "@c/search";
import Cookie from "@u/cookie";
import { _debounce } from "@u/debounce";
import dialogCom from "./dialogCom";
import timeFormat from "@u/timeFormat";
import {
  getGoodsInfoListApi,
  getProductSelectApi,
  updateGoodsInfoApi,
  exportExcelApi,
  deleteGoodsInfoApi,
  getLocalActivityApi
} from "@s/api";
import { GOODSSTATUSLIST, GOODSSTATUS, FLOOROBJ } from "@u/wordbook";

import headText from "@c/headText";
import page from "@c/page";
export default {
  name: "index",
  data() {
    return {
      nowPage: 1,
      total: 0,
      limit: 10,
      pageReset: true,
      hackReset: true,
      ActivityList: [],
      goodsStatusList: GOODSSTATUSLIST,
      prouductSelect: [],
      dialogObj: {
        id: "",
        title: "",
        show: false,
        view: false,
        form: {}
      },
      searchItem: [],
      searchData: {
        categoryId: "",
        productName: "",
        isDraft: "",
        activityId: "",
        productorCategory: 2 //1 特许
      },
      tableData: []
    };
  },
  components: {
    headText,
    page,
    dialogCom,
    Search
  },
  created() {
    this.searchItem = [
      {
        prop: "productName",
        placeholder: "请输入商品名称",
        label: "商品名称：",
        type: "input"
      },
      {
        prop: "categoryId",
        placeholder: "请选择商品分类",
        label: "商品分类：",
        type: "select",
        selectList: this.prouductSelect
      },
      {
        prop: "isDraft",
        placeholder: "请选择商品状态",
        label: "商品状态：",
        type: "select",
        selectList: this.goodsStatusList
      },
      {
        prop: "activityId",
        placeholder: "请选择活动",
        label: "活动：",
        type: "select",
        selectList: this.ActivityList
      }
    ];
  },
  //过滤器
  filters: {
    goodsStatus(val) {
      return GOODSSTATUS[val];
    },
    floorFilter(val) {
      return FLOOROBJ[val];
    }
  },
  mounted() {
    this.productSelect();
    this.getActivityList();
    this.getList();
  },
  methods: {
    onPageChange(val) {
      this.nowPage = val;
      this.getList();
    },
    onSizeChange(val) {
      this.nowPage = 1;
      this.limit = val;
      this.getList();
    },
    // 操作库存
    mangeInventory(val) {
      this.$prompt("正数为增加库存，负数为减少库存", "修改库存", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^-?\d+$/,
        inputErrorMessage: "请输入整数",
        inputValue: ""
      }).then(({ value }) => {
        let json = {
          stock: value,
          id: val.id
        };
        updateGoodsInfoApi(json).then(() => {
          this.$message({
            type: "success",
            message: "库存修改成功"
          });
          this.getList();
        });
      });
    },
    // 活动信息
    getActivityList() {
      getLocalActivityApi().then(res => {
        res = res.list;
        // 特许商品判断权限筛选
        // 查询是否有活动权限
        let getActivityId =
          JSON.parse(localStorage.getItem("mb_userInfo")).activityIds || "";
        if (getActivityId && getActivityId != "0") {
          // 单个活动用户
          getActivityId = getActivityId.split(","); // 字符串转数组
          // 活动权限筛选
          let activityArr = [];
          res.forEach(item => {
            if (getActivityId.indexOf(item.id) > -1) {
              activityArr.push(item);
            }
          });
          this.ActivityList = activityArr;
        } else {
          // 所有活动用户

          this.ActivityList = res;
        }
        let newActivityList = [];
        res.forEach(item => {
          var newItem = {
            id: item.activityId,
            value: item.activityName
          };
          newActivityList.push(newItem);
        });
        this.ActivityList = newActivityList;
        this.searchItem.forEach(item => {
          if (item.prop == "activityId") {
            item.selectList = this.ActivityList;
          }
        });
      });
    },
    productSelect() {
      var json = {
        categoryType: 2 // 1 餐饮
      };
      getProductSelectApi(json).then(res => {
        let newCategoryList = [];
        res.forEach(item => {
          var newItem = {
            id: item.id,
            value: item.categoryName
          };
          newCategoryList.push(newItem);
        });
        this.prouductSelect = newCategoryList;
        this.searchItem.forEach(item => {
          if (item.prop == "categoryId") {
            item.selectList = this.prouductSelect;
          }
        });
      });
    },
    edit(v) {
      this.dialogObj.id = v.id;
      this.dialogObj.form = v;
      this.dialogObj.view = false;
      this.dialogObj.show = true;
      this.dialogObj.title = "编辑商品";
    },
    view(v) {
      this.dialogObj.id = v.id;
      this.dialogObj.view = true;
      this.dialogObj.form = v;
      this.dialogObj.show = true;
      this.dialogObj.title = "商品详情";
    },
    shelf(v) {
      this.$confirm("此操作将上架该商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let json = {
          id: v.id,
          shelfTime: "",
          venueFloor: v.venueFloor, //默认楼层
          offShelfTime: "", // 快捷上架默认下架时间长期不下架
          isDraft: 3 //  3 状态更改上架中
        };
        json.shelfTime = timeFormat.hoursTime(new Date());
        updateGoodsInfoApi(json).then(() => {
          this.getList();
          this.$message({
            type: "success",
            message: "上架成功！"
          });
        });
      });
    },
    offShelf(v) {
      this.$confirm("此操作将下架该商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let json = {
          id: v.id,
          venueFloor: v.venueFloor, //默认楼层
          offShelfTime: "", // 下架默认下架时间上架时间归零
          isDraft: 4 //  4 状态更改已下架
        };
        updateGoodsInfoApi(json).then(() => {
          this.getList();
          this.$message({
            type: "success",
            message: "下架成功！"
          });
        });
      });
    },
    // 搜索事件
    getDataList(val) {
      this.searchData = val;
      this.nowPage = 1;
      this.limit = 10;
      this.pageReset = false;
      this.$nextTick(() => {
        this.getList();
        this.pageReset = true;
      });
    },
    getList() {
      let json = JSON.parse(JSON.stringify(this.searchData));
      json.page = this.nowPage;
      json.limit = this.limit;
      getGoodsInfoListApi(json).then(res => {
        this.hackReset = false;
        this.$nextTick(() => {
          this.tableData = res.list;
          this.total = res.total;
          this.hackReset = true;
        });
      });
    },
    add() {
      this.dialogObj.id = "";
      this.dialogObj.show = true;
      this.dialogObj.view = false;
      this.dialogObj.title = "添加商品";
      this.dialogObj.form.isDraft = 1;
    },
    exp: _debounce(function() {
      let json = JSON.parse(JSON.stringify(this.searchData));
      exportExcelApi(json, "特许商品信息表").then(() => {});
    }),
    deleteGoods(val) {
      this.$confirm("此操作将删除该商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let json = [];
        if (val) {
          json.push(val);
        }
        deleteGoodsInfoApi(json).then(() => {
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功！"
          });
        });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.img-size {
  width: 100px;
  cursor: pointer;
}
</style>
